<?php 
    $_SERVER = [];
    $_SERVER['DOCUMENT_ROOT'] =  dirname(dirname(__FILE__));
    require_once($_SERVER['DOCUMENT_ROOT']."/configures/global.php");
    require_once("connection.php");
    require_once("data_access.php");
    require_once("object_mapping.php");
    function covert_b2b_json_2_hotel_instance($b2b_json,$ean_hotel_instance=NULL)
    {
        if (is_null($ean_hotel_instance))
        {
            $hotel_instance = new Hotel();
        }
        else
        {
            $hotel_instance = $ean_hotel_instance;
        }
        $hotel_instance->wc_uuid = $b2b_json["wcnHotelUuid"];
        $hotel_instance->hotel_wcid = $b2b_json["wcnHotelId"];
        $hotel_instance->service = $b2b_json["hotelServer"];
        $hotel_instance->rating = $b2b_json["hotelStar"];
        $hotel_instance->web_url = $b2b_json["website"];
        $hotel_instance->cert_level = $b2b_json["crtfcnLevel"];
        $hotel_instance->name = $b2b_json["hotelNm"];
        $hotel_instance->latitude = $b2b_json["latitude"];
        $hotel_instance->longitude = $b2b_json["longitude"];
        $hotel_instance->address = $b2b_json["hotelAddr"];
        $hotel_instance->description = html_entity_decode($b2b_json["hotelLongDesc"]);
        $in_door_f = array_map(function($facility){return $facility["facility"];},$b2b_json["indoorFacility"]);
        $gen_f = array_map(function($facility){return $facility["facility"];},$b2b_json["generalFacility"]);
        $out_door_f = array_map(function($facility){return $facility["facility"];},$b2b_json["outdoorFacility"]);
        $hotel_instance->image_head = $b2b_json["hotelMainImg"];
        $hotel_instance->image_normal_set = json_encode(array_map(function($img)
        {
            if (array_key_exists("eanUrl",$img) && !empty($img["eanUrl"]))
            {
                return get_best_quality_images($img["eanUrl"]);
            }
            else
            {
                return $img["wcnUrl"];
            }
        },$b2b_json["hotelImages"]));
        $hotel_instance->image_small_set = json_encode(array_map(function($img)
        {
            if (array_key_exists("eanUrl",$img) && !empty($img["eanUrl"]))
            {
                return $img["eanUrl"];
            }
            else
            {
                return $img["wcnUrl"];
            }
        },$b2b_json["hotelImages"]));
        $facility = [];
        if (count($in_door_f) > 0)
        {
            $facility["in_door"] = $in_door_f;
        }
        if (count($gen_f) > 0)
        {
            $facility["gen_f"] = $gen_f;
        }
        if (count($out_door_f) > 0)
        {
            $facility["out_door_f"] = $out_door_f;
        }
        if (count($facility) > 0)
        {
            $hotel_instance->amenities  = json_encode($facility);
        }
        if ($b2b_json["langCd"] =="en_US") 
        {
            $hotel_instance->lang = "en";
        }
        else
        {
            $hotel_instance->lang = "cn";
        }
        if (array_key_exists("eanHotelid",$b2b_json) && !empty($b2b_json["eanHotelid"]))
        {
            $hotel_instance->ean_id = $b2b_json["eanHotelid"];
        }
        
        if (array_key_exists("checkIn",$b2b_json) && !empty($b2b_json["checkIn"]))
        {
            $hotel_instance->check_in = html_entity_decode($b2b_json["checkIn"]);
        }
        if (array_key_exists("checkOut",$b2b_json) && !empty($b2b_json["checkOut"]))
        {
            $hotel_instance->check_out = html_entity_decode($b2b_json["checkOut"]);
        }
        if (array_key_exists("hotelPolicy",$b2b_json) && !empty($b2b_json["hotelPolicy"]))
        {
            $hotel_instance->policy = html_entity_decode($b2b_json["hotelPolicy"]);
        }
        if (array_key_exists("checkInInstructions",$b2b_json) && !empty($b2b_json["checkInInstructions"]))
        {
            $hotel_instance->checkin_instructions = html_entity_decode($b2b_json["checkInInstructions"]);
        }
        if (array_key_exists("feesDesc",$b2b_json) && !empty($b2b_json["feesDesc"]))
        {
            $hotel_instance->room_fees = html_entity_decode($b2b_json["feesDesc"]);
        }
        return $hotel_instance;
    }
    function convert_ean_json_2_hotel_instance($ean_json)
    {
        $hotel_instance = new Hotel();
        if (array_key_exists("PropertyAmenities",$ean_json))
        {
            $ean_f = array_map(function($a){return preg_replace("/ ? - ?(\d+)/"," : $1 ", $a["amenity"]);},$ean_json["PropertyAmenities"]["PropertyAmenity"]);           
            $hotel_instance->amenities  = json_encode(["Facility"=>$ean_f]);
        }
        if (array_key_exists("HotelDetails",$ean_json))
        {
            if (array_key_exists("numberOfFloors",$ean_json["HotelDetails"]))
            {
                $hotel_instance->floor_count = $ean_json["HotelDetails"]["numberOfFloors"];
            }
            if (array_key_exists("numberOfRooms",$ean_json["HotelDetails"]))
            {
            	$hotel_instance->room_count= $ean_json["HotelDetails"]["numberOfRooms"];
            }
            if (array_key_exists("checkInTime",$ean_json["HotelDetails"]))
            {
            	$hotel_instance->check_in = $ean_json["HotelDetails"]["checkInTime"];
            }
            if (array_key_exists("checkOutTime",$ean_json["HotelDetails"]))
            {
            	$hotel_instance->check_out = $ean_json["HotelDetails"]["checkOutTime"];
            }
            if (array_key_exists("areaInformation",$ean_json["HotelDetails"]))
            {
            	$hotel_instance->area_info = html_entity_decode($ean_json["HotelDetails"]["areaInformation"]);
            }
            if (array_key_exists("roomInformation",$ean_json["HotelDetails"]))
            {
            	$hotel_instance->room_info = html_entity_decode($ean_json["HotelDetails"]["roomInformation"]);
            }
            if (array_key_exists("hotelPolicy",$ean_json["HotelDetails"]))
            {
            	$hotel_instance->policy = html_entity_decode($ean_json["HotelDetails"]["hotelPolicy"]);
            }
            if (array_key_exists("checkInInstructions",$ean_json["HotelDetails"]))
            {
            	$hotel_instance->checkin_instructions = html_entity_decode($ean_json["HotelDetails"]["checkInInstructions"]);
            }
            if (array_key_exists("roomFeesDescription",$ean_json["HotelDetails"]))
            {
            	$hotel_instance->room_fees = html_entity_decode($ean_json["HotelDetails"]["roomFeesDescription"]);
            }
        }
        return $hotel_instance;
    }
    function get_best_quality_images($imgsrc)
    {
        //z for ultra resolution , y for good , b for normal (default)
        $image_flags=["z","y"];
        foreach ($image_flags as $flag)
        {
            $data_src = str_replace("b",$flag,$imgsrc);
            $request = curl_init($data_src);
            curl_setopt($request,CURLOPT_RETURNTRANSFER,TRUE);
            curl_setopt($request, CURLOPT_SSL_VERIFYPEER, false);
            curl_exec($request);
            if (!curl_errno($request))
            {
                if (curl_getinfo($request,CURLINFO_HTTP_CODE) != 404)
                {
                    //echo "Replace " .$imgsrc ." with ".$data_src . "\r\n";
                    return $data_src;
                }
            }
        }
        return $imgsrc;
    }
    function read_ean($ean_id,$len)
    {
        $cid=EANCID;
        $api_key=EANKEY;
        $attempt = 0;
        $max_attempt = MAXATTEMPT;
        $data_src = "https://api.eancdn.com/ean-services/rs/hotel/v3/info?cid=".urlencode($cid)."&locale=".urlencode($len)."&apiKey=".urlencode($api_key)."&xml=".urlencode("<HotelInformationRequest><hotelId>{$ean_id}</hotelId><options>0</options></HotelInformationRequest>");
        $result = [];
        while ($attempt < $max_attempt)
        {
            $request = curl_init($data_src);
            curl_setopt($request,CURLOPT_HEADER,FALSE);
            curl_setopt($request,CURLOPT_RETURNTRANSFER,TRUE);
            curl_setopt($request, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($request,CURLOPT_HTTPHEADER,['Content-Type'=>' application/json']);
            $result = curl_exec($request);
            if (!$result)
            {
                $attempt+=1;
                $sleep_time = FAILINTERVAl;
                echo curl_error($request)."\r\n";
                sleep($sleep_time);
            }
            else
            {
                curl_close($request);
                $result = json_decode($result,true);
                sleep(1.0/8.0);
                break;
            }
        }
        if ($attempt>=$max_attempt)
        {
        	echo "EAN Error!\r\n";
        }
        return $result["HotelInformationResponse"];
        
    }
    function read_b2b()
    {
        $in_process_hotel = 1;
        $certificated_hotel = 0;
        $max_attempt = MAXATTEMPT;
        $attempt = 0;
        $max_hotel_id = 0;
        $per_request_record = 40;
        foreach ([$certificated_hotel,$in_process_hotel] as $q_type)
        {
            //echo $data_src."\r\n";
            while ($attempt < $max_attempt)
            {
                $data_src = B2BHOST. "/lakewood/hotelsDataForB2C!getHotelsData.action?queryType={$q_type}&localMaxHotelID={$max_hotel_id}&recordNumberPerPage={$per_request_record}";
                $request = curl_init($data_src);
                curl_setopt($request,CURLOPT_HEADER,FALSE);
                curl_setopt($request,CURLOPT_RETURNTRANSFER,TRUE);
                $result = curl_exec($request);
                if (!$result)
                {
                    $attempt+=1;
                    echo curl_error($request)."\r\n";
                    sleep(FAILINTERVAl);
                }
                else
                {
                    //echo $result;
                    if (curl_getinfo($request,CURLINFO_HTTP_CODE) == 200)
                    {
                        curl_close($request);
                        
                        $result = json_decode($result,true);
                        //print_r($result);
                        if ($result["st"] == 0)
                        {
                            $attempt = 0;
                            echo "Successful request B2B!\r\n";
                            if ($result["val"]["resultCode"] == -2)//B2B api spec, -2 = result empty
                            {
                                $max_hotel_id = 0;
                                break;
                            }
                            else
                            {
                                $hotels = $result["val"]["result"];
                                foreach ($hotels as $hotel)
                                {
                                    if ((int)$hotel["wcnHotelId"] > $max_hotel_id)
                                    {
                                        $max_hotel_id = (int)$hotel["wcnHotelId"];
                                    }
                                    $hotel_instance = NULL;
                                    if (array_key_exists("eanHotelid",$hotel) && !empty($hotel["eanHotelid"]) )
                                    {
                                        $ean_id = $hotel["eanHotelid"];
                                        $ean_data = [];
                                        $ean_data = read_ean($hotel["eanHotelid"],$hotel["langCd"]);
                                        $hotel_instance = covert_b2b_json_2_hotel_instance($hotel,convert_ean_json_2_hotel_instance($ean_data));
                                         
                                    }
                                    else
                                    {
                                        $hotel_instance = covert_b2b_json_2_hotel_instance($hotel);
                                    }
                                    yield [$hotel["cityNm"],$hotel["countryNm"],$hotel_instance];
                                }
                            }
                        }
                        else
                        {
                            $attempt+=1;
                        }
                    }
                    else
                    {
                        $attempt+=1;
                    }
                }

            }
            if ($attempt>=$max_attempt)
            {
                echo "B2B Error!\r\n";
                break;
            }
        }


    }
    
    
    $processed_uuid = [];
    $auto_id = 1;
    try
    { 
    	foreach (read_b2b() as $data)
    	{
            $conn = create_connection("wc_tmp");
            echo "Processing " .$auto_id . "\r\n";
        	list($city,$country,$hotel) = $data;
        	$city_id = get_city_id($country,$city,"wc_tmp");
        	if (array_key_exists($hotel->wc_uuid,$processed_uuid))
        	{
                $hotel->exist = TRUE;
            	list($cus_id,$e_id,$hotel_id,$c_id) = $processed_uuid[$hotel->wc_uuid];
            	if ($city_id < 0)
            	{
                    $city_id = $c_id;
                    update_city($city_id,$country,$city,$hotel->lang,"wc_tmp");
            	}
        	}
        	else
        	{
                list($cus_id,$e_id,$hotel_id) = [$auto_id,$auto_id,$auto_id];
            	$auto_id+=1;
            	if ($city_id < 0)
            	{
                    $city_id = create_city($country,$city,$hotel->lang,"wc_tmp");
            	}
            }
        	$hotel->customer_id = $cus_id;
        	$hotel->entity_id = $e_id;
        	$hotel->city_id = $city_id;
        	$hotel->hotel_id = $hotel_id;
        	$processed_uuid[$hotel->wc_uuid] = $hotel->save($conn);
            $conn = null;
        }
    }
    catch (Exception $e)
    {
    	echo "\r\nCan i rollback?\r\n";
    	echo "\r\n".$e->getMessage()."\r\n";
    }
    

?>